package com.example.asyncquery.service;

import com.example.asyncquery.model.QueryResult;
import com.example.asyncquery.model.QueryStatus;
import com.example.asyncquery.model.User;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;

@Service
@Slf4j
@RequiredArgsConstructor
public class QueryServiceImpl implements QueryService {

    private final SseEmitterService sseEmitterService;
    
    // 存储查询结果的内存缓存
    private final Map<String, QueryResult<?>> queryResultCache = new ConcurrentHashMap<>();

    @Override
    @Async
    public CompletableFuture<QueryResult<?>> queryById(Long id) {
        String queryId = UUID.randomUUID().toString();
        LocalDateTime startTime = LocalDateTime.now();
        
        // 创建初始状态为PENDING的查询结果
        QueryResult<User> initialResult = QueryResult.<User>builder()
                .queryId(queryId)
                .status(QueryStatus.PENDING)
                .message("查询处理中...")
                .startTime(startTime)
                .build();
        
        // 将初始结果存入缓存
        queryResultCache.put(queryId, initialResult);
        
        // 通过SSE发送初始状态
        sseEmitterService.sendQueryResultUpdate(queryId, initialResult);
        
        // 开始异步处理查询
        return CompletableFuture.supplyAsync(() -> {
            try {
                log.info("开始处理查询ID: {}, 数据ID: {}", queryId, id);
                
                // 模拟耗时操作
                Thread.sleep(5000);
                
                // 模拟根据ID查询用户
                User user = null;
                
                // 成功查询到用户
                if (id > 0 && id <= 100) {
                    user = User.builder()
                            .id(id)
                            .name("用户" + id)
                            .email("user" + id + "@example.com")
                            .department("部门" + (id % 5 + 1))
                            .build();
                    
                    // 更新查询结果为成功
                    QueryResult<User> result = QueryResult.<User>builder()
                            .queryId(queryId)
                            .status(QueryStatus.COMPLETED)
                            .data(user)
                            .message("查询成功")
                            .startTime(startTime)
                            .endTime(LocalDateTime.now())
                            .build();
                    
                    queryResultCache.put(queryId, result);
                    
                    // 通过SSE发送完成状态
                    sseEmitterService.sendQueryResultUpdate(queryId, result);
                    
                    return result;
                } else {
                    // 查询失败
                    QueryResult<User> result = QueryResult.<User>builder()
                            .queryId(queryId)
                            .status(QueryStatus.FAILED)
                            .message("未找到ID为 " + id + " 的用户")
                            .startTime(startTime)
                            .endTime(LocalDateTime.now())
                            .build();
                    
                    queryResultCache.put(queryId, result);
                    
                    // 通过SSE发送失败状态
                    sseEmitterService.sendQueryResultUpdate(queryId, result);
                    
                    return result;
                }
            } catch (Exception e) {
                log.error("查询处理异常: ", e);
                
                // 发生异常，将状态更新为失败
                QueryResult<User> result = QueryResult.<User>builder()
                        .queryId(queryId)
                        .status(QueryStatus.FAILED)
                        .message("查询过程发生错误: " + e.getMessage())
                        .startTime(startTime)
                        .endTime(LocalDateTime.now())
                        .build();
                
                queryResultCache.put(queryId, result);
                
                // 通过SSE发送失败状态
                sseEmitterService.sendQueryResultUpdate(queryId, result);
                
                return result;
            }
        });
    }

    @Override
    public QueryResult<?> getQueryResult(String queryId) {
        return queryResultCache.getOrDefault(queryId, 
                QueryResult.builder()
                        .queryId(queryId)
                        .status(QueryStatus.FAILED)
                        .message("未找到查询记录")
                        .build());
    }
} 